package yixingren.bonus;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

/**
 * Created by JanHan on 16/3/23.
 *
 */
public class BlowListener {

    /**
     * 关于麦克风检测的一些变量，比较重要的是HandlerThread
     */
    private Microphone mic;
    private HandlerThread mCheckMsgThread;
    private Handler mCheckMsgHandler;
    private static final int MSG_UPDATE_INFO = 0x110;
    private Handler mHandler = new Handler();

    private OnBlewListener listener;

    public BlowListener(OnBlewListener listener) {

        this.listener = listener;
        mic = new Microphone();
        initBackThread();
    }

    public void releaseResource() {

        mic.releaseRecorder();
//        mCheckMsgThread.interrupt();
    }

    /**
     * 启动了一个Handler来用looper进行实时的监听。
     */
    private void initBackThread() {

        mCheckMsgThread = new HandlerThread("check-message-coming");
        mCheckMsgThread.start();

        mCheckMsgHandler = new Handler(mCheckMsgThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                checkForUpdate();
                mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
            }
        };
        //一定要启动这个mCheckMsgHandler来接受信息
        mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
    }

    private void checkForUpdate() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

//                invalidate();
                if (mic.getLevel() > 3) {

                    Log.e("TAG", "单纯检测到声音乐乐乐乐乐");
                    System.out.println("检测到声音了！");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    if (mic.getLevel() > 3) {
//                        Log.e("TAG", "这里收到了长长的声音输入，重新绘制图层");
//                        isBlow = true;
                        listener.blew();
                        //invalidate();
//                    }

                } else {
//                    isBlow = false;
                    //invalidate();
                }
            }
        });
    }

    public interface OnBlewListener {

        void blew();
    }
}
